package com.adou.d17;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.util.List;

public class Dom4jTest {
    public static void main(String[] args) throws Exception {
        //1.创建解析器对象
        final SAXReader saxReader = new SAXReader();

        //2.xml读成一个document对象
        final Document document = saxReader.read("d1-helloword-app\\src\\helloworld.xml");

        // 3.从文档对象解析xml所有数据
        final Element rootElement = document.getRootElement();
        System.out.println(rootElement.getName());

        // 4.获取根元素下面一级子元素
        final List<Element> elements = rootElement.elements("user");
        for (Element element : elements) {
            System.out.println(element.getName());
        }

        // 5.获取当前元素下某个子元素
        final Element person = rootElement.element("person");
        System.out.println(person.getText());

        // 6.如果下面有很多子元素，获取第一个
        final Element user = rootElement.element("user");
        System.out.println(user.elementText("name"));

        // 7.获取属性值
        System.out.println(user.attributeValue("id"));
        Attribute attribute = user.attribute("id");
        System.out.println(attribute.getName());

        // 8.
        final List<Attribute> attributes = user.attributes();
        for (Attribute attribute1 : attributes) {
            System.out.println(attribute1.getName() + " //- " + attribute1.getValue());
        }


        // 9.如何获取所有文本内容
        System.out.println(user.elementText("name"));
        System.out.println(user.elementText("password"));

        // 10.
        final Element data = user.element("data");
        System.out.println(data.getText());
        System.out.println(data.getText().trim());


    }
}
